package net.zhuike.novel.app.ui.activity.anount;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;

import net.zhuike.novel.app.R;
import net.zhuike.novel.app.service.UserService;
import net.zhuike.novel.app.ui.activity.MainActivity;
import net.zhuike.novel.app.ui.base.Constant;
import net.zhuike.novel.app.ui.utils.AppUtils;
import net.zhuike.novel.app.ui.utils.SharedPreferencesUtil;
import net.zhuike.novel.app.ui.utils.ToastUtils;

import org.json.JSONObject;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import framework.common.baseui.UeBaseActivity;
import framework.common.runtimepermissions.PermissionsManager;
import framework.common.runtimepermissions.PermissionsResultAction;
import framework.common.zanetwork.UeHttpUrl;
import framework.common.zanetwork.core.ResponseCallback;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by qi.wang on 2017/6/19.
 * 登录
 */

public class LoginActivity extends UeBaseActivity implements View.OnClickListener{
    private EditText username,password;
    private Button login,regsit_btn;
    private TextView forgetpwd_btn,login_check,regirst_btn;
    private int check=1;
    private OkHttpClient mOkHttpClient;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        baseSetContentView(R.layout.activity_login);
        hiddenFooter();
        hiddenHeader();
        hiddenGoBackBtn();
        setTitleText("");
        requestPermissions();
        SharedPreferencesUtil.getInstance().putString(Constant.check, String.valueOf(check));
        initView();
    }
    private void initView(){
        username=(EditText)findViewById(R.id.username);
        password=(EditText)findViewById(R.id.password);
        login=(Button)findViewById(R.id.login);
        login.setOnClickListener(this);
        forgetpwd_btn=(TextView)findViewById(R.id.forgetpwd_btn);
        forgetpwd_btn.setOnClickListener(this);
        regirst_btn=(TextView)findViewById(R.id.regirst_btn);
        regirst_btn.setOnClickListener(this);
        login_check=(TextView)findViewById(R.id.login_check);
        login_check.setOnClickListener(this);
        if(!(SharedPreferencesUtil.getInstance().getString(Constant.phoneNum,"")==null||SharedPreferencesUtil.getInstance().getString(Constant.phoneNum,"").equals(""))){
            username.setText(SharedPreferencesUtil.getInstance().getString(Constant.phoneNum,""));
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.login:
                String usernameVal = username.getText().toString().replace(" ", "");
                String pwd=password.getText().toString();
                if(TextUtils.isEmpty(usernameVal)){
                    ToastUtils.showSingleToast("账号不能为空");
                    return;
                }
                if(TextUtils.isEmpty(pwd)){
                    ToastUtils.showSingleToast("密码不能为空");
                    return;
                }
                login(usernameVal,pwd);
                break;
            case R.id.forgetpwd_btn:
                Intent startForgetPwd=new Intent(this,ForgetPassActivity.class);
                startActivity(startForgetPwd);
                break;
            case R.id.login_check:
                if(check==1) {
                    check=0;
                    SharedPreferencesUtil.getInstance().putString(Constant.check, String.valueOf(check));
                    Drawable drawable = getResources().getDrawable(R.mipmap.select_no);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    login_check.setCompoundDrawables(drawable, null, null, null);
                }else{
                    check=1;
                    SharedPreferencesUtil.getInstance().putString(Constant.check, String.valueOf(check));
                    Drawable drawable = getResources().getDrawable(R.mipmap.select_yes);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    login_check.setCompoundDrawables(drawable, null, null, null);
                }
            case R.id.regirst_btn:
                Intent startRegist=new Intent(this,RegistActivity.class);
                startActivityForResult(startRegist,10);
                break;
        }
    }
    private void jumpToMain(){
        Intent startMain=new Intent(this, MainActivity.class);
        startMain.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(startMain);
        finish();
    }


    public void login(String usernameVal, String pass) {
        try {
            String parmas=usernameVal+"/"+AppUtils.EncoderByMd5(pass);
            mOkHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(30, TimeUnit.SECONDS)       //设置连接超时
                    .readTimeout(60, TimeUnit.SECONDS)          //设置读超时
                    .writeTimeout(60, TimeUnit.SECONDS)          //设置写超时
                    .retryOnConnectionFailure(true)             //是否自动重连
                    .build();
            final Request request = new Request.Builder()
                    .url(UeHttpUrl.getLogin()+parmas)
                    //.addHeader("cookie",SharedPreferencesUtil.getInstance().getString("cookie"))
                    .get()
                    .build();
            Call call = mOkHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        String str=response.body().string();
                        JSONObject obj=new JSONObject(str);
                        if(obj.getString("flag").equals("success")){
                            SharedPreferencesUtil.getInstance().putString(Constant.phoneNum,usernameVal);
                            SharedPreferencesUtil.getInstance().putString(Constant.Token,usernameVal);
                          jumpToMain();
                        }else if(obj.getString("flag").equals("error")){
                            if(obj.getString("data").equals("2")){
                                Message message = new Message();
                                message.what = 1;
                                handlers.sendMessage(message);
                            }else if(obj.getString("data").equals("3")){
                                Message message = new Message();
                                message.what = 2;
                                handlers.sendMessage(message);
                            }else{
                                Message message = new Message();
                                message.what = 3;
                                handlers.sendMessage(message);
                            }
                        }
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
        }
    }
    Handler handlers = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    ToastUtils.showToast("用户或密码不正确");
                    break;
                case 2:
                    ToastUtils.showToast("账号目前还没有激活");
                    break;
                case 3:
                    ToastUtils.showToast("服务器错误");
                    break;
            }
        }
    };
    @TargetApi(23)
    private void requestPermissions() {
        PermissionsManager.getInstance().requestAllManifestPermissionsIfNecessary(this, new PermissionsResultAction() {
            @Override
            public void onGranted() {
//				Toast.makeText(MainActivity.this, "All permissions have been granted", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDenied(String permission) {
                //Toast.makeText(MainActivity.this, "Permission " + permission + " has been denied", Toast.LENGTH_SHORT).show();
            }
        });
    }
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        PermissionsManager.getInstance().notifyPermissionsChange(permissions, grantResults);
    }
    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("登录");
        MobclickAgent.onResume(context);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("登录");
        MobclickAgent.onPause(context);
    }
}
